package org.devf.fork.imsimulator.socket.handler;

import org.devf.fork.imsimulator.help.ApiResultHelp;
import org.devf.fork.imsimulator.socket.Channel;
import org.devf.fork.imsimulator.socket.Ihandler;
import org.devf.fork.imsimulator.socket.dto.BasePackets;
import org.devf.fork.imsimulator.socket.dto.BizType;
import org.devf.fork.imsimulator.socket.handler.listener.ConnectResultListener;
import org.devf.fork.imsimulator.socket.handler.listener.HandlerListener;

import java.util.ArrayList;
import java.util.List;

/**
 * ConnectHandler related
 *
 * @author wanghuafu
 * @since 1.0  2023/9/12 14:37
 */
public class ConnectHandler implements Ihandler {

    private final List<ConnectResultListener> chatListenerList = new ArrayList<>();

    @Override
    public void register(HandlerListener chatListener) {
        chatListenerList.add((ConnectResultListener) chatListener);
    }

    @Override
    public boolean isSupport(BasePackets packets) {
        return packets.getBizType().equals(BizType.CONNECT.name());
    }

    @Override
    public boolean execute(Channel channel, BasePackets packets) {
        if (packets.getAck()){
            System.out.println("收到connect指令Ack消息");
            ApiResultHelp.util.unwrapIfSuccessElse(
                    packets.getContents(),
                    suc->{
                        // 发送心跳
                        Ihandler ihandler = MsgHandlerFactory.HeartHandler();
                        if (ihandler instanceof HeartHandler){
                            ((HeartHandler) ihandler).sendHeartPackets();
                        }
                        notifySuccess(suc);
                    },
                    fail->{
                        System.out.println("connect 指令连接认证失败!");
                        // 更新界面
                        notifyFail(fail);
                    });
        }
        return true;
    }

    private void notifyFail(Object fail) {
        for (ConnectResultListener chatListener : chatListenerList) {
            chatListener.fail(fail.toString());
        }
    }

    private void notifySuccess(Object suc) {
        for (ConnectResultListener chatListener : chatListenerList) {
            chatListener.suc(suc);
        }
    }




}
